package br.com.hsp.system.beans;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import br.com.hsp.system.repository.MedicoClinicaRepository;
import br.com.hsp.users.MedicoClinica;

@ManagedBean
public class MedicoClinicaBean {

	private MedicoClinica medicoClinica = new MedicoClinica();	
		
	private List<MedicoClinica> medicosClinica; 

	public void add() {
		EntityManager manager = this.getManager();
		MedicoClinicaRepository medicoClinicaRepository = new MedicoClinicaRepository(manager);
	
		if (this.medicoClinica.getId() == null) {
			medicoClinicaRepository.add(this.medicoClinica);
		} else {
			medicoClinicaRepository.atualiza(this.medicoClinica);
		}
		this.medicoClinica = new MedicoClinica();
	}

	public void preparaAlteracao() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		MedicoClinicaRepository repository = new MedicoClinicaRepository(manager);
		this.medicoClinica = repository.procura(id);

	}
	

	public void remove() {
		System.out.println("remove");
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		MedicoClinicaRepository repository = new MedicoClinicaRepository(manager);
		repository.remove(id);
		this.medicoClinica = null;
		this.medicosClinica = null;
	}
	

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");

	}

	public List<MedicoClinica> getMedicosClinica() {
		if (this.medicosClinica == null) {
			EntityManager manager = this.getManager();
			MedicoClinicaRepository repository = new MedicoClinicaRepository(manager);
			this.medicosClinica = repository.getLista();
		}
		return this.medicosClinica;
	}

	public MedicoClinica getMedicoClinica() {
		return medicoClinica;
	}

	public void setMedicoClinica(MedicoClinica medicoClinica) {
		this.medicoClinica = medicoClinica;
	}

}
